<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <a-form :label-col="{ md: { span: 6 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }">
        <a-row>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="客户" name="supplier">
              <a-auto-complete v-model:value="sellWhere.supplier" :options="supplierOptions" placeholder="请输入客户"
                @select="supplier_onSelect" @search="supplier_onSearch" @blur="supplier_blur" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="产品" name="productname">
              <a-auto-complete v-model:value="sellWhere.productname_val" :options="productnameOptions"
                placeholder="请输入产品" @select="productname_onSelect" @search="productname_onSearch"
                @blur="productname_blur" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="规格" name="specification">
              <a-input v-model:value.trim="sellWhere.specification" placeholder="规格" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="出库单号">
              <a-input v-model:value.trim="sellWhere.keywords" placeholder="出库单号" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="开始出库">
              <a-date-picker v-model:value="sellWhere.date1" valueFormat="YYYY-MM-DD" placeholder="开始出库"
                class="ele-fluid" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="结束出库">
              <a-date-picker v-model:value="sellWhere.date2" valueFormat="YYYY-MM-DD" placeholder="结束出库"
                class="ele-fluid" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="收款">
              <a-select v-model:value="sellWhere.state" placeholder="请选择">
                <a-select-option value="">请选择</a-select-option>
                <a-select-option value="已收款">已收款</a-select-option>
                <a-select-option value="未收款">未收款</a-select-option>
                <a-select-option value="部分收款">部分收款</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="开票">
              <a-select v-model:value="sellWhere.invoice" placeholder="请选择">
                <a-select-option value="">请选择</a-select-option>
                <a-select-option value="已开票">已开票</a-select-option>
                <a-select-option value="未开票">未开票</a-select-option>
                <a-select-option value="无">无</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item :wrapper-col="{ span: 24 }">
              <em></em>
              <a-space>
                <a-button type="primary" @click="sellReload">查询</a-button>
                <a-button @click="sellReset">重置</a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- 表格 -->
      <ele-pro-table ref="sellTableRef" row-key="id" :columns="columns" :datasource="datasource" :scroll="{ x: 1000 }"
        cacheKey="sell">
        <template #toolbar>
          <a-space>
            <a-button type="primary" @click="sellOpenEdit()" v-any-permission="['store:sell:save']">
              <template #icon>
                <plus-outlined />
              </template>
              <span>添加</span>
            </a-button>
          </a-space>
        </template>
        <template #summary>
          <a-table-summary-row>
            <a-table-summary-cell :col-span="3">
              未付金额:
              <a-typography-text type="danger">
                {{ priceResult.unpaid }}
              </a-typography-text>
            </a-table-summary-cell>
            <a-table-summary-cell :col-span="2">
              总金额:
              <a-typography-text type="danger">
                {{ priceResult.total }}
              </a-typography-text>
            </a-table-summary-cell>
          </a-table-summary-row>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'state'">
            <span :class="{ 'Crimson': record.state == '未收款', 'MediumSlateBlue': record.state == '部分收款' }">{{
      record.state }}</span>
            <a-switch v-if="record.state !== '已收款'" :checked="record.state === '已收款'"
              @change="(checked) => editState(checked, record, { state: '已收款' })" />
          </template>
          <template v-else-if="column.key === 'invoice'">
            <span :class="{ 'Crimson': record.invoice == '未开票' }">{{ record.invoice }}</span>
            <a-switch v-if="record.invoice === '未开票'" checked="record.invoice === '已开票'"
              @change="(checked) => editState(checked, record, { invoice: '已开票' })" />
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a @click="showPrint(record)" v-any-permission="['store:sell:print']">打印</a>
              <a @click="sellOpenEdit(record)" v-any-permission="['store:sell:update']">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定要删除此项吗？" @confirm="sellRemove(record)">
                <a class="ele-text-danger" v-any-permission="['store:sell:remove']">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 销售单添加、修改弹窗 -->
    <ele-modal :width="460" v-model:visible="sellVisible_modal" :confirm-loading="loading"
      :title="sellIsUpdate ? '修改销售单' : '添加销售单'" position="center" :body-style="{ paddingBottom: '8px' }" @ok="sellSave"
      :maskClosable="false">
      <a-form ref="sellFormRef" :model="sellForm" :rules="sellRules" :label-col="{ md: { span: 7 }, sm: { span: 24 } }"
        :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
        <a-row :gutter="16">
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="销售单号" name="code">
              <a-input allow-clear :maxlength="200" placeholder="请输入销售单号" v-model:value="sellForm.code"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="供应商" name="supplier">
              <a-input allow-clear :maxlength="200" placeholder="请输入供应商" v-model:value="sellForm.supplier"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="销售日期" name="selltime">
              <a-input allow-clear :maxlength="200" placeholder="请输入销售日期" v-model:value="sellForm.selltime"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="未付款金额" name="unpaid">
              <a-input allow-clear :maxlength="200" placeholder="请输入未付款金额" v-model:value="sellForm.unpaid"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="状态 未收款 部分收款 已收款" name="state">
              <a-input allow-clear :maxlength="200" placeholder="请输入状态 未收款 部分收款 已收款" v-model:value="sellForm.state"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="开票 已开票 未开票" name="invoice">
              <a-input allow-clear :maxlength="200" placeholder="请输入开票 已开票 未开票" v-model:value="sellForm.invoice"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="总金额" name="total">
              <a-input allow-clear :maxlength="200" placeholder="请输入总金额" v-model:value="sellForm.total"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="备注" name="remark">
              <a-input allow-clear :maxlength="200" placeholder="请输入备注" v-model:value="sellForm.remark"
                autocomplete="off" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </ele-modal>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { toDateString } from 'ele-admin-pro';
import useFormData from '@/utils/use-form-data';
import { message } from 'ant-design-vue';
import { TIME_OUT } from '@/config/damon';
import { useRouter } from 'vue-router';
import dayjs from 'dayjs';
import { reloadPageTab, finishPageTab, setRouteReload, getRouteTabKey, setPageTabTitle, removePageTab } from '@/utils/page-tab-util';

import { pageSell, removeSell, removeSellAndSon, addSell, updateSell, updateTableState } from '@/api/store/sell';
import { listCustomerSel } from '@/api/store/customer'
import { listProductSelUnique } from '@/api/store/product'

let router = useRouter()
// 表格实例
const sellTableRef = ref(null);

// 表格列配置
const columns = ref([
  {
    key: 'index',
    width: 48,
    align: 'center',
    fixed: 'left',
    hideInSetting: true,
    customRender: ({ index }) => index + (sellTableRef.value?.tableIndex ?? 0)
  },
  {
    title: '销售单号',
    dataIndex: 'code',
    key: 'code',
    sorter: true
  },
  {
    title: '客户',
    dataIndex: 'supplier',
    key: 'supplier',
    sorter: true
  },
  {
    title: '销售日期',
    dataIndex: 'selltime',
    key: 'selltime',
    sorter: true
  },
  {
    title: '未付金额',
    dataIndex: 'unpaid',
    key: 'unpaid',
    sorter: true
  },
  {
    title: '总金额',
    dataIndex: 'total',
    key: 'total',
    sorter: true
  },
  {
    title: '收款',
    dataIndex: 'state',
    key: 'state',
    sorter: true
  },
  {
    title: '开票',
    dataIndex: 'invoice',
    key: 'invoice',
    sorter: true
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    sorter: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    hideInTable: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '创建人',
    dataIndex: 'createName',
    key: 'createName',
    hideInTable: true,
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    hideInTable: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '更新人',
    dataIndex: 'updateName',
    key: 'updateName',
    hideInTable: true,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    hideInSetting: true
  }
]);

// 表单数据
const { form: sellWhere, resetFields } = useFormData({
  username: '',
  sex: undefined,
  keywords: '',
  entrytime: '',
});

// 表格数据源
let priceResult = reactive({})
const datasource = async ({ page, limit, where, orders }) => {
  let data_temp = {}
  orders.sort = orders.sort == 'updateTime' ? 'update_time' : orders.sort
  orders.sort = orders.sort == 'createTime' ? 'create_time' : orders.sort
  await pageSell({ ...where, ...orders, page, limit }).then(data => {
    data_temp = data.data
    priceResult.unpaid = data.priceResult.unpaid
    priceResult.total = data.priceResult.total
  })
  return new Promise((resolve) => {
    resolve(data_temp)
  })
};

/* 搜索 */
const sellReload = () => {
  sellTableRef?.value?.reload({ page: 1, where: sellWhere });
};
const sellReload2 = () => {
  sellTableRef?.value?.reload();
};

let sellWhere_timeout = 0
watch(() => sellWhere, (val) => {
  clearTimeout(sellWhere_timeout)
  sellWhere_timeout = setTimeout(() => {
    sellReload();
  }, TIME_OUT);
},
  { deep: true }
)


/* 修改收款,开票状态 */
const editState = (checked, row, op) => {
  let a = JSON.parse(JSON.stringify(row))
  a = Object.assign(a, op)
  updateTableState(a)
    .then((msg) => {
      Object.assign(row, op)
      message.success(msg.message);
    })
    .catch((e) => {
      message.error(e.message);
    });
};


/*  重置 */
const sellReset = () => {
  resetFields();
  sellReload();
};

// 当前选中数据
const sellCurrent = ref(null);

// 弹窗是否打开
const sellVisible_modal = ref(false);

// 是否是修改
const sellIsUpdate = ref(false);

// 提交状态
const loading = ref(false);

//
const sellFormRef = ref(null);

// 表单数据
const { form: sellForm, resetFields: sellResetFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
});

// 表单验证规则
const sellRules = reactive({
  name: [
    {
      required: true,
      message: '请输入名称',
      type: 'string',
    }
  ],
});


//防止重复刷新
//客户下拉列表
let supplier_m_timeout = 0
const supplierOptions = ref([]);
const supplier_onSearch = searchText => {
  clearTimeout(supplier_m_timeout)
  supplier_m_timeout = setTimeout(() => {
    listCustomerSel({ 'name': searchText }).then(msg => {
      supplierOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
supplier_onSearch('')
const supplier_onSelect = (value2, option2) => {
  // let a = supplierOptions.value.find((item)=> {return item.value=value})
  sellWhere.supplier = option2.label
  sellWhere.supplierId = option2.value
};
const supplier_m_change = (value2) => {
  // let a = supplierOptions.value.find((item)=> {return item.value=value2})
  // sellWhere.supplier_val=a.label
  // sellWhere.supplier=a.label
};
const supplier_blur = () => {
  // sellWhere.supplier_val = sellWhere.supplier
};


//产品名称下拉列表
let productname_m_timeout = 0
const productnameOptions = ref([]);
const productname_onSearch = searchText => {
  clearTimeout(productname_m_timeout)
  productname_m_timeout = setTimeout(() => {
    listProductSelUnique({ name: searchText }).then(msg => {
      productnameOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
productname_onSearch('')
const productname_onSelect = (value2, option2) => {
  // let a = productnameOptions.value.find((item)=> {return item.value=value})
  sellWhere.productname_val = option2.name
  sellWhere.productname = option2.name
  // sellWhere.productnameId = option2.value
  // sellWhere.specification = option2.specification
  // sellWhere.liweight = option2.liWeight
  // sellWhere.lengths = option2.lengths
  // sellWhere.negative = option2.negative
  // sellWhere.code = option2.code
};
// const productname_blur = () => {
//   sellWhere.productname_val = sellWhere.productname
// };
let productname_val_m_timeout = 0
watch(() => sellWhere.productname_val, (val) => {
  clearTimeout(productname_val_m_timeout)
  productname_val_m_timeout = setTimeout(() => {
    sellWhere.productname = sellWhere.productname_val
  }, TIME_OUT);
},
  { deep: true }
)
/* 打开打印页面 */
const showPrint = (record) => {
  router.push({ path: '/store/sell_print', query: { id: record?.id } })
  // sellResetFormFields();
  // sellFormRef.value?.clearValidate();
  // sellCurrent.value = record?? {};
  // sellVisible_modal.value = true;
  // Object.assign(sellForm, record ?? {});
  // sellIsUpdate.value = !!record;
};

//防止重复点击  防抖
let t = true
/* 打开编辑弹窗 */
const sellOpenEdit = (record) => {
  if (!t) { return false }
  t = false
  setTimeout(() => { t = true }, 500);
  // removePageTab({ key: '/store/sell_main', active: '/store/sell_main' });
  // setTimeout(() => {
  //   router.push({ path: '/store/sell_main', query: { id: record?.id } })
  // }, 300);
  sessionStorage.setItem('sell','on')
  router.push({ path: '/store/sell_main', query: { id: record?.id } })
};

/* 保存编辑 */
const sellSave = () => {
  if (!sellFormRef.value) {
    return;
  }
  sellFormRef.value.validate().then(() => {
    loading.value = true;
    const saveOrUpdate = sellIsUpdate.value ? updateSell : addSell;
    saveOrUpdate(sellForm).then((msg) => {
      loading.value = false;
      message.success(msg);
      sellVisible_modal.value = false;
      sellReload2();
    }).catch((e) => {
      loading.value = false;
      message.error(e.message);
    });
  }).catch(() => {
  });
};

/* 删除单个 */
const sellRemove = (record) => {
  const hide = message.loading('请求中..', 0);
  removeSellAndSon(record.id).then((msg) => {
    hide();
    message.success(msg);
    sellReload2();
  }).catch((e) => {
    hide();
    message.error(e.message);
  });
};
</script>
<script>
export default {
  name: 'Sell'
};
</script>
<style lang="less" scoped>
@import "@/assets/css/public.less";

.re {
  background-color: @button-pay;
}
</style>
